import { AppDetail, AppItem } from "@/types/app";
import { invoke } from "@tauri-apps/api/core";
import { retryOperation } from "../utils";

/**
 * 获取应用详细信息
 * @param category 应用分类
 * @param pkgname 应用包名
 * @returns Promise<AppInfoItem>
 */
export async function getAppInfo(category: string, pkgname: string): Promise<AppDetail> {
  try {
    return await retryOperation(async () => {
        const appInfo = await invoke<AppDetail>("get_app_info", {
            category,
            pkgname,
          });
          return appInfo;
      });
  } catch (error) {
    throw new Error(`获取应用信息失败: ${error}`);
  }
}

/**
 * 搜索所有应用
 * @param query 搜索关键词
 * @returns Promise<AppItem[]>
 */
export async function searchAllApps(query: string): Promise<AppItem[]> {
  try {
    // 从后端获取数据并转换字段名称
    const rawApps = await retryOperation(async () => {
      return await invoke<Array<{
        More: string,
        Name: string,
        Pkgname: string,
        Tags?: string,
        Update: string,
        icon?: string,
        category?: string
      }>>("search_all_apps", { query });
    });

    // 将后端返回的大写字段名转换为前端使用的小写格式
    return rawApps.map(app => ({
      more: app.More,
      name: app.Name,
      pkgname: app.Pkgname,
      tags: app.Tags,
      update: app.Update,
      icon: app.icon,
      category: app.category
    }));
  } catch (error) {
    console.error("搜索应用失败:", error);
    throw new Error(`搜索应用失败: ${error}`);
  }
}

